package com.xm.utils.common;


import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * @author xiumin
 * @email xiumin1993@outlook.com
 */
public abstract class Desensitize extends JsonSerializer<String> {
    private static boolean desensitizeFlag = false;

    public static void openDesensitize() {
        desensitizeFlag = true;
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (desensitizeFlag && StringUtils.isNotBlank(s)) {
            jsonGenerator.writeString(apply(s));
        } else {
            jsonGenerator.writeString(s);
        }
    }

    public abstract String apply(String s);

    public static class MobileDesensitize extends Desensitize {
        @Override
        public String apply(String s) {
            return StrUtil.hide(s, 3, s.length() - 4);
        }
    }

    public static class EmailDesensitize extends Desensitize {
        @Override
        public String apply(String s) {
            return StrUtil.hide(s, 3, s.lastIndexOf("@"));
        }
    }


    public static class IdCardNoDesensitize extends Desensitize {
        @Override
        public String apply(String s) {
            return StrUtil.hide(s, 2, s.length() - 2);
        }
    }

    public static class NameDesensitize extends Desensitize {
        @Override
        public String apply(String s) {
            if (s.length() > 2) {
                return StrUtil.hide(s, 1, s.length() - 1);
            }
            return StrUtil.hide(s, 1, s.length());
        }
    }

    public static class AddrDesensitize extends Desensitize {
        @Override
        public String apply(String s) {
            return StrUtil.hide(s, 1, s.length());
        }
    }

}
